<template>
  <div class="dashboard-container">
    <h2 class="page-title">数据看板</h2>

    <!-- 核心数据卡片 -->
    <el-row :gutter="20" class="summary-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card user-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-info">
              <p class="card-label">总用户数</p>
              <p class="card-value">{{ summary.totalUsers || 0 }}</p>
              <p class="card-extra">今日新增: {{ summary.todayNewUsers || 0 }}</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card product-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><Box /></el-icon>
            </div>
            <div class="card-info">
              <p class="card-label">商品总数</p>
              <p class="card-value">{{ summary.totalProducts || 0 }}</p>
              <p class="card-extra">在售: {{ summary.availableProducts || 0 }}</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card order-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><ShoppingCart /></el-icon>
            </div>
            <div class="card-info">
              <p class="card-label">订单总数</p>
              <p class="card-value">{{ summary.totalOrders || 0 }}</p>
              <p class="card-extra">今日: {{ summary.todayOrders || 0 }}</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card post-card">
          <div class="card-content">
            <div class="card-icon">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="card-info">
              <p class="card-label">帖子总数</p>
              <p class="card-value">{{ summary.totalPosts || 0 }}</p>
              <p class="card-extra">今日: {{ summary.todayNewPosts || 0 }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
            </div>
          </template>
          <div ref="userTrendChart" class="chart"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
            </div>
          </template>
          <div ref="salesTrendChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>帖子发布趋势</span>
            </div>
          </template>
          <div ref="postTrendChart" class="chart"></div>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品状态分布</span>
            </div>
          </template>
          <div ref="productStatusChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热门帖子和活跃用户 -->
    <el-row :gutter="20" class="tables-row">
      <el-col :xs="24" :md="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>热门帖子 Top10</span>
            </div>
          </template>
          <el-table :data="hotPosts" stripe style="width: 100%">
            <el-table-column prop="title" label="标题" show-overflow-tooltip />
            <el-table-column prop="likeCount" label="点赞" width="80" />
            <el-table-column prop="commentCount" label="评论" width="80" />
            <el-table-column prop="viewCount" label="浏览" width="80" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :md="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>活跃用户 Top10</span>
            </div>
          </template>
          <el-table :data="activeUsers" stripe style="width: 100%">
            <el-table-column prop="nickName" label="昵称" show-overflow-tooltip />
            <el-table-column prop="postCount" label="发帖" width="80" />
            <el-table-column prop="commentCount" label="评论" width="80" />
            <el-table-column prop="productCount" label="商品" width="80" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Box, ShoppingCart, ChatDotRound } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '@/utils/request'

const summary = ref({})
const hotPosts = ref([])
const activeUsers = ref([])

const userTrendChart = ref(null)
const salesTrendChart = ref(null)
const postTrendChart = ref(null)
const productStatusChart = ref(null)

// 获取核心数据统计
const getSummary = async () => {
  try {
    const response = await request.get('/admin/dashboard/summary')
    if (response.code === 0) {
      summary.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 初始化用户增长趋势图表
const initUserTrendChart = async () => {
  try {
    const response = await request.get('/admin/dashboard/userTrend')
    if (response.code === 0) {
      const data = response.data
      const dates = data.map(item => item.date)
      const counts = data.map(item => item.count)

      const chart = echarts.init(userTrendChart.value)
      chart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: counts,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#5470c6'
          },
          areaStyle: {
            color: 'rgba(84, 112, 198, 0.2)'
          }
        }]
      })

      // 响应式
      window.addEventListener('resize', () => {
        chart.resize()
      })
    }
  } catch (error) {
    console.error('获取用户趋势失败', error)
  }
}

// 初始化销售趋势图表
const initSalesTrendChart = async () => {
  try {
    const response = await request.get('/admin/dashboard/salesTrend')
    if (response.code === 0) {
      const data = response.data
      const dates = data.map(item => item.date)
      const amounts = data.map(item => item.amount)

      const chart = echarts.init(salesTrendChart.value)
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>销售额: ¥{c}'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: amounts,
          type: 'bar',
          itemStyle: {
            color: '#91cc75'
          }
        }]
      })

      window.addEventListener('resize', () => {
        chart.resize()
      })
    }
  } catch (error) {
    console.error('获取销售趋势失败', error)
  }
}

// 初始化帖子发布趋势图表
const initPostTrendChart = async () => {
  try {
    const response = await request.get('/admin/dashboard/postTrend')
    if (response.code === 0) {
      const data = response.data
      const dates = data.map(item => item.date)
      const counts = data.map(item => item.count)

      const chart = echarts.init(postTrendChart.value)
      chart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: counts,
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#fac858'
          }
        }]
      })

      window.addEventListener('resize', () => {
        chart.resize()
      })
    }
  } catch (error) {
    console.error('获取帖子趋势失败', error)
  }
}

// 初始化商品状态分布图表
const initProductStatusChart = () => {
  if (!summary.value.productsByStatus) return

  const data = summary.value.productsByStatus.map(item => ({
    name: item.status === 'available' ? '在售' : item.status === 'sold' ? '已售' : item.status === 'reserved' ? '预定' : '下架',
    value: item.count
  }))

  const chart = echarts.init(productStatusChart.value)
  chart.setOption({
    tooltip: {
      trigger: 'item'
    },
    series: [{
      type: 'pie',
      radius: '60%',
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })

  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 获取热门帖子
const getHotPosts = async () => {
  try {
    const response = await request.get('/admin/dashboard/hotPosts')
    if (response.code === 0) {
      hotPosts.value = response.data
    }
  } catch (error) {
    console.error('获取热门帖子失败', error)
  }
}

// 获取活跃用户
const getActiveUsers = async () => {
  try {
    const response = await request.get('/admin/dashboard/activeUsers')
    if (response.code === 0) {
      activeUsers.value = response.data
    }
  } catch (error) {
    console.error('获取活跃用户失败', error)
  }
}

onMounted(async () => {
  await getSummary()
  await nextTick()
  
  initUserTrendChart()
  initSalesTrendChart()
  initPostTrendChart()
  initProductStatusChart()
  getHotPosts()
  getActiveUsers()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 24px 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.summary-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: #fff;
}

.user-card .card-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.product-card .card-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.order-card .card-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.post-card .card-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-info {
  flex: 1;
}

.card-label {
  margin: 0;
  font-size: 14px;
  color: #999;
}

.card-value {
  margin: 8px 0;
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.card-extra {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.charts-row,
.tables-row {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  border-radius: 8px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart {
  width: 100%;
  height: 350px;
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }

  .card-value {
    font-size: 24px;
  }

  .chart {
    height: 300px;
  }
}
</style>

